Page({
  data: {
    gender: 1,
    name: '',
    mobile: '',
    idcardFrontUrl: '',
    idcardBackUrl: '',
  },

  onLoad({ point,building, room }) {
    this.setData({ point, building, room })
  },

  verifyName() {
    const reg = /^[\u4e00-\u9fa5]{2,5}$/
    // 验证业主姓名
    const valid = reg.test(this.data.name.trim())
    // 验证结果提示
    if (!valid) wx.utils.toast('请填写真实中文姓名!')
    // 返回验证结果
    return valid
  },
  verifyMobile() {
    const reg = /^[1][3-8][0-9]{9}$/
    const vaild = reg.test(this.data.mobile)

    if(!vaild) wx.utils.toast('请填写正确的手机号码!')
    return vaild
  },
  verifyPicture() {
    const vaild = !!this.data.idcardFrontUrl && !!this.data.idcardBackUrl
    return vaild
  },
  async uploadPicture(e) {
    const type = e.mark.type
    console.log(type);

    const media =await wx.chooseMedia({
      count: 1,
      mediaType: ['image'],
      sizeType: ['compressed'],
    })

    wx.uploadFile({
      url: wx.http.baseURL + '/upload',
      filePath: media.tempFiles[0].tempFilePath,
      name: 'file',
      header: {
        Authorization: getApp().token,
      },

      success: (res) => {
        const data = JSON.parse(res.data)
        if(data.code !== 10000)  return wx.showToast({ title: '上传图片失败!', icon: 'none' })

        this.setData({
          [type]: data.data.url,
        })
      }
    }) 
  },
  async submitForm() {
    if (!this.verifyName()) return
    if (!this.verifyMobile()) return
    if (!this.verifyPicture()) return


    // 删除一些数据
    delete this.data.__webviewId__

    const { code } = await wx.http.post('/room', this.data)
    if(code !== 10000)  return wx.utils.toast('添加房屋失败！')

    wx.navigateBack({
      delta: 4,
    })
  },
  removePicture(ev) {
    // 移除图片的类型（身份证正面或反面）
    const type = ev.mark?.type
    this.setData({ [type]: '' })
  },
})
